import filter from '../../utils/filter.js'
import request from '../../utils/request.js'
import config from '../../utils/config.js'
const app = getApp()

Page({
  pageNum: 1, //页码
  pageCount: 0, //总页数

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    titleBarHeight: app.globalData.titleBarHeight,
    userInfo: null,
    userType: 0,
    done: false, //列表是否全部加载完
    list: [],
    classList: [],
    classId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'options': options
    })

    filter(this).then(res => {
      this.getList()
      // this.getClassList()
    }).catch(err => {
      wx.reLaunch({
        url: '/pages/login/login',
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      'userInfo': app.globalData.userInfo,
      'userType': wx.getStorageSync('userType')
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.pageNum = 1
    this.pageCount = 0
    this.setData({
      done: false
    })
    this.getList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.done) {
      return false
    }
    this.pageNum++
    this.getList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const openid = wx.getStorageSync('openid')
    return {
      title: '智能急救培训',
      path: '/pages/startup/startup?referrerId=' + (openid || '')
    }
  },

  bindLink(e) {
    if (!e.currentTarget.dataset.url) {
      return false;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },

  getList() {
    request.get('/api/weChatMini/v1/news/list', {
      page: this.pageNum,
      limit: 20,
      newsClassId: this.data.classId
    }).then(res => {
      wx.stopPullDownRefresh()
      this.pageCount = res.page.totalPage
      let arr = this.data.list
      if (this.pageNum == 1) {
        arr = []
      }
      for (let item of res.page.list) {
        if (!item.readNum) {
          item._readNum = '0'
        } else {
          item._readNum = item.readNum > 9999 ? '9999+' : item.readNum + ''
        }
        item._createTime = item.createTime.substr(0, 10)
        item.picture = item.listSmallPic ? item.listSmallPic : '/images/default_avatar.jpg'
      }
      this.setData({
        done: res.page.totalPage <= this.pageNum,
        list: arr.concat(res.page.list)
      })
    }).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  bindChangeClass(e) {
    this.setData({
      classId: e.currentTarget.dataset.id
    })
    this.getList()
  },

  getClassList() {
    request.get('/api/weChatMini/v1/news/newsClass/list', {
      page: 1,
      limit: 100
    }).then(res => {
      this.setData({
        classList: res.page.list
      })
    })
  },

  bindAuth() {
    wx.navigateTo({
      url: '../auth/auth?isBack=1',
    })
  },


  scanLogin(code) {
    wx.request({
      url: config.host + '/api/weChatMini/v1/user/device/login',
      header: {
        token: wx.getStorageSync('token')
      },
      method: 'PUT',
      data: {
        deviceSnMoment: code || '',
        userId: wx.getStorageSync('userId')
      },
      success: res => {
        if (res.data.code == 0) {
          wx.showToast({
            title: '登录成功',
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        }
      },
      fail: err => {
        console.log(3333)
      }
    })
  },

  joinScenes(id) {
    wx.request({
      url: `${config.host}/api/weChatMini/v1/user/scenesVideoJoin/${id}`,
      header: {
        token: wx.getStorageSync('token')
      },
      method: 'GET',
      success: res => {
        if (res.data.code == 0) {
          wx.showToast({
            title: '操作成功',
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false
          })
        }
      },
      fail: err => {
        console.log(3333)
      }
    })
  },

  bindScan() {
    wx.scanCode({
      success: res => {
        const arr = res.result.split('/')
        const str = arr.pop()
        const type = Number(str.charAt(0))
        const userType = wx.getStorageSync('userType')
        if (type === 3) {
          this.joinScenes(str.substr(1))
        } else if (userType == type) {
          this.scanLogin(str.substr(1))
        } else {
          wx.showModal({
            title: '提示',
            content: '用户身份不匹配',
            showCancel: false
          })
        }
      }
    })
  }
})